package com.wfh.picture.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.RandomUtil;
import com.wfh.picture.exception.BusinessException;
import com.wfh.picture.exception.ErrorCode;
import com.wfh.picture.exception.ThrowUtils;
import com.wfh.picture.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author FengHuan Wang
 * @Date 2025/5/9 14:20
 * @Version 1.0
 */

/**
 * @deprecated 已经废弃，改为使用upload包的模板方法
 */
@Service
@Slf4j
@Deprecated
public class FileManager {

    @Resource
    private ObsManager obsManager;

    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPrefix){
        // 校验图片
        validPicture(multipartFile);
        // 图片上传地址
        String filename = multipartFile.getOriginalFilename();
        String uuid = RandomUtil.randomString(16);
        // 自己拼接文件上传路径
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),
                uuid, FileUtil.getSuffix(filename));
        String uploadPath = String.format("%s/%s", uploadPrefix, uploadFileName);
        // 上传文件
        File file = null;
        try {
            file = File.createTempFile(uploadPath, null);
            multipartFile.transferTo(file);
            String uploadUrl = obsManager.upload(file, uploadPath);
            BufferedImage image = ImageIO.read(file);
            int width = image.getWidth();
            int height = image.getHeight();
            double ratio = (double) width /(double) height;
            // 封装返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(uploadUrl);
            uploadPictureResult.setPicName(FileUtil.mainName(filename));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(width);
            uploadPictureResult.setPicHeight(height);
            uploadPictureResult.setPicScale(ratio);
            uploadPictureResult.setPicFormat(FileNameUtil.extName(filename));
            // 返回
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("文件{}上传失败：{}", uploadPath, e.getMessage());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传文件失败");
        }finally {
            // 临时文件清理
            delTempFile(file, uploadPath);
        }
    }

    /**
     * 临时文件清理
     * @param file
     * @param uploadPath
     */
    private static void delTempFile(File file, String uploadPath) {
        if (file != null){
            // 删除临时文件
            boolean delete = file.delete();
            if (!delete){
                log.error("删除临时文件{}失败", uploadPath);
            }
        }
    }

    /**
     * 校验图片
     * @param multipartFile
     */
    private void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
        // 文件大小
        long size = multipartFile.getSize();
        final long ONE_M = 2014 * 1024;
        ThrowUtils.throwIf(size > ONE_M, ErrorCode.PARAMS_ERROR, "图片大小不能超过2M");
        // 文件格式
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final List<String> ALLOW = Arrays.asList("jpeg", "jpg", "png");
        ThrowUtils.throwIf(!ALLOW.contains(suffix), ErrorCode.PARAMS_ERROR, "图片格式不支持");
    }
}
